package org.budo.activiti.util;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.delegate.VariableScope;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.activiti.engine.impl.persistence.entity.VariableInstance;

/**
 * @author lmw
 */
public class VariableScopeUtil {
    public static Map<String, Object> getVariable(VariableScope variableScope) {
        ExecutionEntityImpl entityImpl = (ExecutionEntityImpl) variableScope;
        ExecutionEntityImpl parent = entityImpl.getParent();

        Map<String, VariableInstance> variableInstances = parent.getVariableInstances();
        HashMap<String, Object> map = new HashMap<String, Object>();
        for (String key : variableInstances.keySet()) {
            VariableInstance variableInstance = variableInstances.get(key);
            map.put(key, variableInstance.getTextValue());
        }

        map.put("activityId", entityImpl.getActivityId()); // 流程设计时给这个步骤搞的ID
        return map;
    }

    public static String getVariable(VariableScope variableScope, String variableName) {
        ExecutionEntityImpl entityImpl = (ExecutionEntityImpl) variableScope;
        ExecutionEntityImpl parent = entityImpl.getParent();

        Map<String, VariableInstance> variableInstances = parent.getVariableInstances();
        VariableInstance variableInstance = variableInstances.get(variableName);
        return variableInstance.getTextValue();
    }

    public static void setVariable(VariableScope variableScope, String variableName, Object variableValue) {
        ExecutionEntityImpl entityImpl = (ExecutionEntityImpl) variableScope;
        ExecutionEntityImpl parent = entityImpl.getParent();
        parent.setVariable(variableName, variableValue);
    }
}